/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.documents.common.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Administrator
 */
public class SynchroToken {

    private static SynchroToken instance = new SynchroToken();

    public static SynchroToken getInstance() {
        return instance;
    }

    protected SynchroToken() {
        super();
    }

    public synchronized boolean isTokenValid(HttpServletRequest request) {
        return this.isTokenValid(request, false);
    }

    public synchronized boolean isTokenValid(
            HttpServletRequest request,
            boolean reset) {
        // Retrieve the current session for this request 
        HttpSession session = request.getSession(false);
        if (session == null) {
            return false;
        }
        // Retrieve the transaction token from this session, and 
        // reset it if requested 
        String saved = (String) session.getAttribute(ItsConstants.TRANSACTION_TOKEN_KEY);
        if (saved == null) {
            return false;
        }
        if (reset) {
            this.resetToken(request);
        }
        // Retrieve the transaction token included in this request 
        String token = request.getParameter(ItsConstants.REQUEST_TOKEN_KEY);
        if (token == null) {
            return false;
        }
        return saved.equals(token);
    }

    public synchronized void resetToken(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session == null) {
            return;
        }
        session.removeAttribute(ItsConstants.TRANSACTION_TOKEN_KEY);
    }

    public synchronized void saveToken(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String token = generateToken(request);
        if (token != null) {
            session.setAttribute(ItsConstants.TRANSACTION_TOKEN_KEY, token);
        }
    }

    public String generateToken(HttpServletRequest request) {
        HttpSession session = request.getSession();
        try {
            byte id[] = session.getId().getBytes();
            byte now[] = new Long(System.currentTimeMillis()).toString().getBytes();

            try {
                MessageDigest md = MessageDigest.getInstance("MD5");
                md.update(id);
                md.update(now);
                return this.toHex(md.digest());
            } catch (NoSuchAlgorithmException ex) {
                Logger.getLogger(SynchroToken.class.getName()).log(Level.SEVERE, null, ex);
                return null;
            }

        } catch (IllegalStateException e) {
            return null;
        }
    }

    public String toHex(byte buffer[]) {
        StringBuffer sb = new StringBuffer();
        String s = null;
        for (int i = 0; i < buffer.length; i++) {
            s = Integer.toHexString((int) buffer[i] & 0xff);
            if (s.length() < 2) {
                sb.append('0');
            }
            sb.append(s);
        }
        return sb.toString();
    }
}
